package com.g9.blog.service.impl;

import com.g9.blog.common.Response;
import com.g9.blog.common.Result;
import com.g9.blog.entity.Articleimg;
import com.g9.blog.entity.Users;
import com.g9.blog.repository.ArticleimgRepository;
import com.g9.blog.repository.TheUserRepository;
import com.g9.blog.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Auther: Graycat
 * @Date: 2020/9/8 15:30
 * Create by lwj.
 */

@Service
@Transactional
public class MyUserServiceImpl implements MyUserService {

    @Autowired
    private TheUserRepository theUserRepository;
    @Autowired
    ArticleimgRepository articleimgRepository;

    @Value("${lalala.save-path}")
    String rootPath;
    @Value("${lalala.img-path}")
    String imgPath;

    Response response = new Response();
    public void printSelf(){
        System.out.println("成功进入sercice");
    }

    @Override
    public List<Users> findAllByUsername(String username) {
        return theUserRepository.findAllByUsername(username);
    }

    @Override
    public List<Users> findAll() {
        return theUserRepository.findAll();
    }

    @Override
    public void deleteById(int userId) {
        theUserRepository.deleteById(userId);
    }

    @Override
    public void save(Users users) {
        theUserRepository.save(users);
    }

    @Override
    // 上传文件到resources下
    public String uploadIcon(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return "文件格式错误，要求为jpg,jpeg,gif,png.";
        }
//        当前项目位置
//        String rootPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\userImg\\";
//        System.out.println("rootPath: " + rootPath);
        
//        String fileName = file.getOriginalFilename();
        // 根据时间戳命名文件
        String fileName = new Date().getTime()+"ddd."+suffix;

        String filePath = rootPath;
        File testfile = new File(filePath);
        // 若不存在myimg文件夹，则创建文件夹
        if (!testfile.exists()) {
            testfile.mkdir();
        }
        File dest = new File(filePath + fileName);
        System.out.println("文件存储位置：" + filePath + fileName);
        try {
            file.transferTo(dest);    //保存文件到本地的filepath
            //成功返回地址src
            return filePath+fileName;
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("上传失败");
        }
        return null;
    }

    // 更新用户头像
    public Result updateUserIcon( MultipartFile file , Users users){
        String uploadResultSrc = uploadIcon(file);
        if (uploadResultSrc==""||uploadResultSrc==null){
            return response.makeErrRsp("上传失败");
        }
        users.setIcon(uploadResultSrc);
        theUserRepository.save(users);
        return response.makeOKRsp("上传成功。");
    }

    @Override
    // 上传图片
    public String uploadImg(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return "文件格式错误，要求为jpg,jpeg,gif,png.";
        }
        // 根据时间戳命名文件
        String fileName = new Date().getTime() + "x." + suffix;
        String filePath = imgPath;

        File testfile = new File(filePath);
        // 若不存在myimg文件夹，则创建文件夹
        if (!testfile.exists()) {
            testfile.mkdir();
        }
        File dest = new File(filePath + fileName);
        System.out.println("文件存储位置：" + filePath + fileName);
        try {
            file.transferTo(dest);    //保存文件到本地的filepath
            //成功返回地址src
            return filePath + fileName;
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("上传失败");
        }
        return null;
    }

    public Result saveImgPathToSql( String path, int articleId ){
        Articleimg articleimg = new Articleimg();
        articleimg.setUrl(path);
        articleimg.setArticleId(articleId);
        articleimgRepository.save(articleimg);
        return response.makeOKRsp("上传成功。");
    }






    @Override
    public Result updateUserIconByUsername(MultipartFile file, String username) {
//        String uploadResultSrc = uploadIcon(file);
//        if (uploadResultSrc==""||uploadResultSrc==null){
//            return response.makeErrRsp("上传失败");
//        }
//        Users user = (Users) theUserRepository.findAllByUsername(username);
//        user.setIcon(uploadResultSrc);
//        theUserRepository.save(user);
        return response.makeOKRsp("上传成功。");
    }


}
